<template>
  <div class="version-container">
    <!-- 顶部工具栏 -->
    <div class="version-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="createRepository">
          <el-icon><Plus /></el-icon>
          新建仓库
        </el-button>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索仓库..."
          style="width: 300px; margin-left: 16px;"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
      <div class="toolbar-right">
        <el-button-group>
          <el-button :type="viewMode === 'grid' ? 'primary' : 'default'" @click="viewMode = 'grid'">
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button :type="viewMode === 'list' ? 'primary' : 'default'" @click="viewMode = 'list'">
            <el-icon><List /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 仓库列表 -->
    <div class="repository-list" :class="{ 'grid-view': viewMode === 'grid', 'list-view': viewMode === 'list' }">
      <div 
        v-for="repository in repositories"
        :key="repository.id"
        class="repository-card"
        @click="openRepository(repository)"
      >
        <div class="repository-header">
          <div class="repo-info">
            <h3 class="repo-name">{{ repository.name }}</h3>
            <el-tag 
              :type="getTypeTag(repository.type)"
              size="small"
            >
              {{ getTypeText(repository.type) }}
            </el-tag>
          </div>
          <el-dropdown @command="(command) => handleCommand(command, repository)" @click.stop>
            <el-button type="text" size="small">
              <el-icon><MoreFilled /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="clone">克隆</el-dropdown-item>
                <el-dropdown-item command="settings">设置</el-dropdown-item>
                <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        
        <p class="repo-description">{{ repository.description || '暂无描述' }}</p>
        
        <div class="repo-stats">
          <div class="stat-item">
            <el-icon><Share /></el-icon>
            <span>{{ repository.branchCount }} 分支</span>
          </div>
          <div class="stat-item">
            <el-icon><Clock /></el-icon>
            <span>{{ repository.commitCount }} 提交</span>
          </div>
          <div class="stat-item">
            <el-icon><User /></el-icon>
            <span>{{ repository.collaboratorCount }} 协作者</span>
          </div>
        </div>
        
        <div class="repo-meta">
          <div class="meta-left">
            <el-avatar :size="20" :src="repository.creatorAvatar" />
            <span class="creator">{{ repository.creatorName }}</span>
          </div>
          <div class="meta-right">
            <span class="last-activity">{{ formatTime(repository.lastActivityTime) }}</span>
          </div>
        </div>
        
        <div class="repo-actions">
          <el-button size="small" type="text" @click.stop="viewBranches(repository)">
            <el-icon><Share /></el-icon>
            分支
          </el-button>
          <el-button size="small" type="text" @click.stop="viewCommits(repository)">
            <el-icon><Clock /></el-icon>
            提交
          </el-button>
          <el-button size="small" type="text" @click.stop="viewIssues(repository)">
            <el-icon><Warning /></el-icon>
            问题
          </el-button>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button @click="loadMore" :loading="loading">加载更多</el-button>
    </div>

    <!-- 创建仓库对话框 -->
    <el-dialog v-model="showCreateRepo" title="创建仓库" width="600px">
      <el-form :model="repoForm" label-width="100px">
        <el-form-item label="仓库名称" required>
          <el-input v-model="repoForm.name" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库描述">
          <el-input v-model="repoForm.description" type="textarea" placeholder="请输入仓库描述" />
        </el-form-item>
        <el-form-item label="仓库类型">
          <el-radio-group v-model="repoForm.type">
            <el-radio value="PUBLIC">公开</el-radio>
            <el-radio value="PRIVATE">私有</el-radio>
            <el-radio value="INTERNAL">内部</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="初始化">
          <el-checkbox v-model="repoForm.initWithReadme">添加 README 文件</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateRepo = false">取消</el-button>
        <el-button type="primary" @click="handleCreateRepo">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getRepositories, 
  searchRepositories,
  createRepository,
  deleteRepository
} from '@/api/version'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const viewMode = ref('grid')
const repositories = ref([])
const showCreateRepo = ref(false)
const loading = ref(false)
const hasMore = ref(true)

// 分页参数
const pagination = reactive({
  page: 1,
  size: 20
})

// 表单数据
const repoForm = reactive({
  name: '',
  description: '',
  type: 'PUBLIC',
  initWithReadme: true
})

// 获取仓库列表
const getRepos = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const params = {
      page: reset ? 1 : pagination.page,
      size: pagination.size
    }
    
    const response = await getRepositories(params)
    if (response.code === 200) {
      const newRepos = response.data.records || []
      if (reset) {
        repositories.value = newRepos
        pagination.page = 1
      } else {
        repositories.value.push(...newRepos)
      }
      
      hasMore.value = newRepos.length === pagination.size
      if (!reset) {
        pagination.page++
      }
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索仓库
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    getRepos(true)
    return
  }
  
  loading.value = true
  try {
    const response = await searchRepositories(searchKeyword.value, {
      page: 1,
      size: pagination.size
    })
    if (response.code === 200) {
      repositories.value = response.data.records || []
      hasMore.value = false
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  getRepos()
}

// 创建仓库
const createRepository = () => {
  showCreateRepo.value = true
}

// 处理创建仓库
const handleCreateRepo = async () => {
  try {
    const response = await createRepository(repoForm)
    if (response.code === 200) {
      showCreateRepo.value = false
      Object.assign(repoForm, { name: '', description: '', type: 'PUBLIC', initWithReadme: true })
      getRepos(true)
      ElMessage.success('创建成功')
    }
  } catch (error) {
    console.error('创建仓库失败:', error)
    ElMessage.error('创建仓库失败')
  }
}

// 打开仓库
const openRepository = (repository) => {
  router.push(`/version/repository/${repository.id}`)
}

// 查看分支
const viewBranches = (repository) => {
  router.push(`/version/repository/${repository.id}/branches`)
}

// 查看提交
const viewCommits = (repository) => {
  router.push(`/version/repository/${repository.id}/commits`)
}

// 查看问题
const viewIssues = (repository) => {
  router.push(`/version/repository/${repository.id}/issues`)
}

// 处理命令
const handleCommand = (command, repository) => {
  switch (command) {
    case 'clone':
      handleClone(repository)
      break
    case 'settings':
      handleSettings(repository)
      break
    case 'delete':
      handleDelete(repository)
      break
  }
}

// 克隆仓库
const handleClone = (repository) => {
  ElMessage.info('克隆功能开发中...')
}

// 仓库设置
const handleSettings = (repository) => {
  router.push(`/version/repository/${repository.id}/settings`)
}

// 删除仓库
const handleDelete = (repository) => {
  ElMessageBox.confirm(`确认要删除仓库"${repository.name}"吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRepository(repository.id)
      ElMessage.success('删除成功')
      getRepos(true)
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 工具函数
const getTypeTag = (type) => {
  const typeMap = {
    'PUBLIC': 'success',
    'PRIVATE': 'danger',
    'INTERNAL': 'warning'
  }
  return typeMap[type] || 'info'
}

const getTypeText = (type) => {
  const textMap = {
    'PUBLIC': '公开',
    'PRIVATE': '私有',
    'INTERNAL': '内部'
  }
  return textMap[type] || type
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleDateString()
}

// 页面加载
onMounted(() => {
  getRepos(true)
})
</script>

<style lang="scss" scoped>
.version-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.version-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
  
  .toolbar-left {
    display: flex;
    align-items: center;
  }
}

.repository-list {
  &.grid-view {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 16px;
  }
  
  &.list-view {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
}

.repository-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
  
  .repository-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
    
    .repo-info {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .repo-name {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
      }
    }
  }
  
  .repo-description {
    margin: 0 0 16px 0;
    color: #666;
    line-height: 1.5;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  
  .repo-stats {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
    
    .stat-item {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 14px;
      color: #666;
    }
  }
  
  .repo-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    font-size: 12px;
    color: #666;
    
    .meta-left {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
  
  .repo-actions {
    display: flex;
    gap: 12px;
    border-top: 1px solid #f0f0f0;
    padding-top: 12px;
  }
}

.load-more {
  text-align: center;
  margin: 20px 0;
}

@media (max-width: 768px) {
  .version-container {
    padding: 12px;
  }
  
  .repository-list.grid-view {
    grid-template-columns: 1fr;
  }
}
</style>
